<template>
  <div class="app-container">
    <el-row :gutter="20">
      <splitpanes :horizontal="appStore.device === 'mobile'" class="default-theme">
        <!--部门数据-->
        <pane size="16">
          <el-col>
            <div class="head-container">
              <el-input v-model="deptName" placeholder="部门名称" clearable prefix-icon="Search" class="mb-10px" />
            </div>
            <div class="head-container">
              <el-tree
                :data="deptOptions"
                :props="{ label: 'name', children: 'children' }"
                :expand-on-click-node="false"
                :filter-node-method="filterNode"
                ref="deptTreeRef"
                node-key="id"
                highlight-current
                default-expand-all
                @node-click="handleNodeClick" />
            </div>
          </el-col>
        </pane>
        <!--用户数据-->
        <pane size="84">
          <el-col>
            <el-form :model="searchForm" ref="searchFormRef" inline v-show="showSearch">
              <el-form-item label="用户名称" prop="like.user_name" class="w-200px">
                <el-input v-model="searchForm.like.user_name" placeholder="请输入" clearable @keyup.enter="search" />
              </el-form-item>
              <el-form-item label="手机号码" prop="like.phone" class="w-200px">
                <el-input v-model="searchForm.like.phone" placeholder="请输入" clearable @keyup.enter="search" />
              </el-form-item>
              <el-form-item label="状态" prop="where.status" class="w-140px">
                <el-select v-model="searchForm.where.status" placeholder="用户状态" clearable>
                  <el-option
                    v-for="dict in sys_normal_disable"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="子部门" prop="contain" class="w-150px">
                <el-select v-model="searchForm.contain" placeholder="子部门">
                  <el-option label="不包含" :value="0" />
                  <el-option label="包含" :value="1" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="Search" @click="search">搜索</el-button>
                <el-button icon="Refresh" @click="reset">重置</el-button>
              </el-form-item>
            </el-form>
            <div class="mb-8px w-full">
              <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPerm="['system:admin:add']"
                >新增</el-button
              >
              <el-button
                type="success"
                plain
                icon="Edit"
                :disabled="ids.length !== 1"
                @click="handleEdit"
                v-hasPerm="['system:admin:edit']"
                >修改</el-button
              >
              <el-button
                type="danger"
                icon="Delete"
                :disabled="!ids.length"
                @click="handleDelete"
                v-hasPerm="['system:admin:delete']"
                >删除</el-button
              >
              <el-button type="info" plain icon="Upload" @click="handleImport" v-hasPerm="['system:admin:import']"
                >导入</el-button
              >
              <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPerm="['system:admin:export']"
                >导出</el-button
              >
              <right-toolbar v-model:showSearch="showSearch" @refresh="getList" v-model:columns="columns" />
            </div>

            <el-table v-loading="loading" :data="listData" @selection-change="handleSelection">
              <el-table-column type="selection" width="50" align="center" />

              <template v-for="item in columns">
                <el-table-column
                  align="center"
                  :key="item.key"
                  :prop="item.key"
                  :label="item.label"
                  :show-overflow-tooltip="!!item.overflow"
                  :width="item.width"
                  v-if="item.show">
                  <template v-slot="{ row }">
                    <span v-if="item.key === 'deptName'">{{ row.deptName.join(', ') }}</span>
                    <span v-else-if="item.key === 'roleName'">{{ row.roleName.join(', ') }}</span>
                    <span v-else-if="item.key === 'status'">
                      <el-switch v-model="row.status" active-value="1" inactive-value="0" @change="handleStatus(row)" />
                    </span>
                    <span v-else-if="item.key === 'create_time'">{{
                      parseTime(row.create_time, '{y}-{m}-{d} {h}:{i}')
                    }}</span>
                    <span v-else>{{ row[item.key] }}</span>
                  </template>
                </el-table-column>
              </template>

              <el-table-column label="操作" align="center" width="150" class-name="small-padding">
                <template #default="{ row }">
                  <el-tooltip content="修改" placement="top">
                    <el-button
                      link
                      type="primary"
                      icon="Edit"
                      @click="handleEdit(row)"
                      v-hasPerm="['system:admin:edit']" />
                  </el-tooltip>
                  <el-tooltip content="删除" placement="top">
                    <el-button
                      link
                      type="primary"
                      icon="Delete"
                      @click="handleDelete(row)"
                      v-hasPerm="['system:admin:delete']" />
                  </el-tooltip>
                  <el-tooltip content="重置密码" placement="top">
                    <el-button
                      link
                      type="primary"
                      icon="Key"
                      @click="handleResetPwd(row)"
                      v-hasPerm="['system:admin:reset-pwd']" />
                  </el-tooltip>
                  <el-tooltip content="分配角色" placement="top">
                    <el-button
                      link
                      type="primary"
                      icon="CircleCheck"
                      @click="handleAuthRole(row)"
                      v-hasPerm="['system:admin:auth-role']" />
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table>
            <pagination
              v-show="total > 0"
              :total="total"
              v-model:page="searchForm.pageNum"
              v-model:limit="searchForm.pageSize"
              @pagination="getList" />
          </el-col>
        </pane>
      </splitpanes>
    </el-row>

    <admin-form v-model="formShow" :row="formData" :module-name="moduleName" @submit="getList" v-if="formShow" />
  </div>
</template>

<script setup name="Admin">
  import { Splitpanes, Pane } from 'splitpanes'
  import 'splitpanes/dist/splitpanes.css'
  import useAppStore from '@/store/modules/app'
  import { listAdminApi, delAdminApi, changeAdminStatusApi, resetAdminPwdApi, exportAdminApi } from '@/api/system/admin'
  import { selectDeptApi } from '@/api/system/dept'
  import AdminForm from './form.vue'

  const moduleName = ref('用户')
  const router = useRouter()
  const appStore = useAppStore()
  const { proxy } = getCurrentInstance()
  const showSearch = ref(true)

  // 列显隐信息
  const columns = ref([
    { key: 'id', label: `编号`, show: true, width: 70 },
    { key: 'user_name', label: `用户名称`, show: true, overflow: true },
    { key: 'nick_name', label: `用户昵称`, show: true, overflow: true },
    { key: 'deptName', label: `部门`, show: true, overflow: true },
    { key: 'roleName', label: `角色`, show: true, overflow: true },
    { key: 'phone', label: `手机号码`, show: true, overflow: true },
    { key: 'status', label: `状态`, show: false },
    { key: 'create_time', label: `创建时间`, show: false, overflow: true }
  ])

  const searchForm = ref({
    pageNum: 1,
    pageSize: 10,
    contain: 0,
    deptId: undefined,
    like: { user_name: undefined, phone: undefined },
    where: { status: undefined }
  })
  const { sys_normal_disable } = proxy.useDict('sys_normal_disable')
  const rootRole = proxy.useInitLoad('root_role_id')

  // 根据名称筛选部门树
  const deptName = ref('')
  const deptTreeRef = useTemplateRef('deptTreeRef')
  watch(deptName, val => {
    deptTreeRef.value.filter(val)
  })

  // 初始化加载
  onMounted(() => {
    getList()
    getDeptOptions()
  })

  // 查询用户列表
  const listData = ref([])
  const loading = ref(true)
  const total = ref(0)
  function getList() {
    loading.value = true
    listAdminApi(searchForm.value).then(res => {
      listData.value = res?.list || []
      total.value = res?.total
      loading.value = false
    })
  }

  // 搜索重置
  const searchFormRef = useTemplateRef('searchFormRef')
  function search() {
    searchForm.value.pageNum = 1
    getList()
  }
  function reset() {
    searchFormRef.value.resetFields()
    searchForm.value.deptId = undefined
    deptTreeRef.value.setCurrentKey(null)
    search()
  }

  // 新增和编辑
  const formData = ref(null)
  const formShow = ref(false)
  function handleAdd() {
    formData.value = null
    formShow.value = true
  }
  function handleEdit(row) {
    const editId = row?.id || ids.value.join(',')
    if (!editId) return proxy.$modal.msgError('参数缺失')
    formData.value = { id: editId }
    formShow.value = true
  }

  // 查询部门下拉树结构
  const deptOptions = ref(undefined)
  function getDeptOptions() {
    selectDeptApi().then(res => {
      deptOptions.value = proxy.listToTree(res?.list || [])
    })
  }

  // 选择条数
  const ids = ref([])
  function handleSelection(selection) {
    ids.value = selection.map(item => item.id)
  }

  // 部门过滤搜索
  const filterNode = (value, data) => {
    if (!value) return true
    return data.name.indexOf(value) !== -1
  }

  // 部门节点单击事件
  function handleNodeClick(data) {
    searchForm.value.deptId = data.id
    search()
  }

  // 删除按钮操作
  function handleDelete(row) {
    const userIds = row?.id || ids.value.join(',')
    if (!userIds) return proxy.$modal.msgWarning('未选择数据')
    proxy.$modal
      .confirm('是否确认删除用户编号为"' + userIds + '"的数据项？')
      .then(function () {
        return delAdminApi(userIds)
      })
      .then(() => {
        getList()
        proxy.$modal.msgSuccess('删除成功')
      })
      .catch(() => {})
  }

  /** 导出按钮操作 */
  function handleExport() {
    exportAdminApi(searchForm.value)
  }

  /** 用户状态修改  */
  function handleStatus(row) {
    let text = row.status === '1' ? '启用' : '停用'
    proxy.$modal
      .confirm('确认要"' + text + '""' + row.user_name + '"用户吗?')
      .then(function () {
        return changeAdminStatusApi(row.id, row.status)
      })
      .then(() => {
        proxy.$modal.msgSuccess(text + '成功')
      })
      .catch(function () {
        row.status = row.status === '0' ? '1' : '0'
      })
  }
  // 重置密码按钮操作
  const initPassword = ref('')
  function handleResetPwd(row) {
    proxy.$modal
      .prompt('请输入"' + row.user_name + '"的新密码', '提示', {
        inputType: 'password',
        inputValue: initPassword.value,
        inputPattern: /^.{6,20}$/,
        inputErrorMessage: '用户密码长度必须介于 6 和 20 之间',
        inputValidator: value => {
          if (/<|>|"|'|\||\\/.test(value)) return '不能包含非法字符：< > " \' \\\ |'
        }
      })
      .then(({ value }) => {
        resetAdminPwdApi(row.id, value).then(() => {
          proxy.$modal.msgSuccess('修改成功，新密码是：' + value)
        })
      })
      .catch(() => {})
  }

  // 跳转角色分配
  function handleAuthRole(row) {
    const adminId = row?.id || ''
    if (!adminId) return proxy.$modal.msgWarning('参数缺失')
    router.push({ name: 'AuthRole', params: { adminId } })
  }

  /** 导入按钮操作 */
  function handleImport() {
    upload.title = '用户导入'
    upload.open = true
  }
</script>
